﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Skywave.Globalization
{
    public static class NationalID
    {
        public static bool CheckIran(string id)
        {
            bool r = false;
            if (!string.IsNullOrEmpty(id))
            {
                if (id.Length == 10 && StringHelper.IsAllDigit(id))
                {
                    bool isAllDigitSame = true;
                    int digitPrev = -1, digit;
                    for (int i = 1; i <= 10; i++)
                    {
                        digit = int.Parse(id.Substring(i - 1, 1));
                        if (i > 1 && isAllDigitSame && digit != digitPrev)
                            isAllDigitSame = false;
                        digitPrev = digit;
                    }
                    if (!isAllDigitSame)
                    {
                        int sum = 0;
                        for (int i = 1; i <= 9; i++)
                        {
                            sum += int.Parse(id.Substring(i - 1, 1)) * (11 - i);
                        }
                        //
                        int controlDigit = int.Parse(id.Substring(9, 1));
                        //
                        int remainder = sum % 11;
                        //
                        if (remainder < 2)
                            r = (remainder == controlDigit);
                        else
                            r = (11 - remainder == controlDigit);
                    }
                }
            }
            return r;
        }
    }
}
